import { createLocalStorage } from '/@/utils/cache/index';
import { ref, computed, Ref, unref } from 'vue';
import { useAppSettingStoreWithOut } from '/@/store/modules/appSetting';
import cookies from '../../../utils/cookie/index';
import { getTenantLogoAndName } from '../../../api/tenant-mgmt/tenant';
import { useGlobSetting } from '../../../hooks/setting/index';

export enum LoginStateEnum {
  LOGIN,
  REGISTER,
  RESET_PASSWORD,
}

const currentState = ref(LoginStateEnum.LOGIN);

export function useFormValid<T>(formRef: Ref<any>) {
  async function validForm() {
    const form = unref(formRef);
    if (!form) return;
    const data = await form.validate();
    return data as T;
  }

  return { validForm };
}

export function useLoginState() {
  function setLoginState(state: LoginStateEnum) {
    currentState.value = state;
  }

  const getLoginState = computed(() => currentState.value);

  function handleBackLogin() {
    setLoginState(LoginStateEnum.LOGIN);
  }

  return { setLoginState, getLoginState, handleBackLogin };
}

export function getLocalUserName(): string {
  const LocalStorage = createLocalStorage();
  const username = LocalStorage.get('login_username');
  return username;
}

export function setLocalUserName(username: string): void {
  const LocalStorage = createLocalStorage();
  LocalStorage.set('login_username', username);
}

export async function getAppLogo() {
  const appSettingStore = useAppSettingStoreWithOut();
  let appLogoPath;
  let displayName;
  try {
    const { tenantLogo, tenantName } = await getTenantLogoAndName(window.location.hostname);
    appLogoPath = tenantLogo ? tenantLogo : '/admin/hw_logo.png';
    displayName = tenantName ? tenantName : 'SaaS DreamWorks';
  } catch {
    appLogoPath = '/src/assets/images/hw_logo.png';
    displayName = 'SaaS DreamWorks';
  }
  appSettingStore.setAppLogoPath(appLogoPath);
  appSettingStore.setTenantName(displayName);
}

export function changeHTMLTitle(name?: string) {
  const tenantName = name ? name : cookies.get('tenantName');
  const { title } = useGlobSetting();
  if (tenantName && tenantName != 'undefined') {
    document.querySelector('title').innerText = tenantName;
  } else {
    document.querySelector('title').innerText = title;
  }
}

export function changeFavicon(src?: string) {
  const appLogoPath = src ? src : cookies.get('appLogoPath');
  if (appLogoPath) {
    const link = document.createElement('link');
    const oldLink = document.getElementById('dynamic-favicon');
    link.id = 'dynamic-favicon';
    link.rel = 'shortcut icon';
    link.href = appLogoPath;
    if (oldLink) {
      document.head.removeChild(oldLink);
    }
    document.head.appendChild(link);
  }
}

export const replaceLogoAndName = async () => {
  const appSettingStore = useAppSettingStoreWithOut();
  const logoPath = appSettingStore.getAppLogoPath;
  if (!logoPath && logoPath != 'undefined') {
    await getAppLogo();
  }
  changeHTMLTitle();
  changeFavicon();
};
